﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Kangaroo.Configuration;
using Kangaroo.Controls;
using Kangaroo.DAL.SqlServer;
using Kangaroo.DAL.SqlServer.Tests;
using Kangaroo.Model;

namespace Kangaroo.AlarmGenerator
{
    public partial class Form1 : Form
    {
        private readonly Dictionary<ChannelInfo, MapMarker> _markers =
            new Dictionary<ChannelInfo, MapMarker>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog();
            if(openFileDialog.ShowDialog() != DialogResult.OK)
            {
                Application.Exit();
            }
            Config.Load(openFileDialog.FileName);
            pictureBox1.Load("map.png");
            foreach(var channelPosition in Config.Instance.ChannelPositions)
            {
                var marker = new MapMarker(channelPosition.Channel, pictureBox1.Size,
                    FromPointOnMap(new Point(channelPosition.X, channelPosition.Y),
                        pictureBox1.ClientSize, pictureBox1.Image.Size));
                marker.IconClick += new EventHandler(marker_IconClick);
                pictureBox1.Controls.Add(marker);
                _markers.Add(channelPosition.Channel, marker);
            }
            pictureBox1.Resize += picMap_Resize;
            SqlHelper.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=Kangaroo;Integrated Security=True;";
        }

        void marker_IconClick(object sender, EventArgs e)
        {
            var clickedChannel = ((MapMarker)sender).Channel;
            DalTestHelper.CreateAlarm(new AlarmInfo
            {
                Channel = clickedChannel,
                AlarmTime = DateTime.Now,
                AlarmLevel = 5,
                AlarmType = "数据有误",
                AlarmValue = 0.1F
            });
        }

        private void picMap_Resize(object sender, EventArgs e)
        {
            foreach(var marker in _markers.Values)
            {
                marker.UpdateParentSize(pictureBox1.ClientSize);
            }
        }

        private static Point FromPointOnMap(
            Point pointOnMap, Size pictureSize, Size mapSize)
        {
            var x = (int)Math.Round(pointOnMap.X * 1.0 / mapSize.Width * pictureSize.Width);
            var y = (int)Math.Round(pointOnMap.Y * 1.0 / mapSize.Height * pictureSize.Height);
            return new Point(x, y);
        }
    }
}
